package com.yuntsg.ruiijn.databse_search.service;


import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import co.elastic.clients.elasticsearch.ElasticsearchClient;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.yuntsg.nnsfcp.common.utils.UserUtil;
import com.yuntsg.ruiijn.databse_search.BaseService;
import com.yuntsg.ruiijn.databse_search.entity.FileDetails;
import com.yuntsg.ruiijn.databse_search.entity.FileDetailsTxt;
import com.yuntsg.ruiijn.databse_search.entity.FileRecord;
import com.yuntsg.ruiijn.databse_search.mapper.FileRecordsMapper;
import common.util.CutImageUtil;
import common.util.ExtractUtil;
import common.util.MinioUtil;
import common.vo.Scenario;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

@Service
@Slf4j
@DS("master")

@SuppressWarnings("all")
public class FileRecordsService extends BaseService<FileRecordsMapper, FileRecord> {

    @Autowired
    private MinioUtil minioUtil;
    @Autowired
    private CutImageUtil cutImageUtil;
    @Autowired
    private ExtractUtil extractUtil;
    @Autowired
    private FileDetailService detailService;
    @Autowired
    private FileDetailTxtService detailTxtService;
    @Autowired
    private FeatureService featureService;
    @Autowired
    private ElasticsearchClient restClient;

    @Value("${upload.path}")
    public String uploadPath;

    @Resource
    UserUtil userUtil;


    /**
     * @param inputStream
     * @param rid
     * @param userId
     * @param type        1 word ,2 pdf
     */
    @SneakyThrows
    public boolean extractFiles(InputStream inputStream, Integer rid, Integer userId, Integer type, String path, Integer spilt) {
        List<FileDetails> fileDetails = new ArrayList<>();
        if (type == 0) {
            fileDetails = extractUtil.extract0(rid, userId, path);
        } else if (type == 1) {
            fileDetails = extractUtil.extractWord(inputStream, rid, userId);
        } else if (type == -1) {
            fileDetails = extractUtil.extractPdfBox(rid, userId, path);
        } else if (type == -2) {
            fileDetails = extractUtil.extractPdfBoxForFull(rid, userId, path);
        } else {
            fileDetails = extractUtil.extractPdf(inputStream, rid, userId);
        }
        if (fileDetails.size() == 0) {
            return false;
        }
        fileDetails.stream().forEach(f -> {
            detailService.saveOrUpdate(f.setRid(rid));
            if (type == -2) {
                return;
            }
            if (spilt == 1) {//如果走拆分
                if (f.getTpye() == 2) {
                    List<FileDetails> work = cutImageUtil.workNoUid(f.getPath(), f.getId(), f.getRid(), -1, userId);
                    if (work.size() > 0) {
                        detailService.saveOrUpdateBatch(work);
                        System.out.println("拆出来的图片数量为___" + work.size());
                    }
                    detailService.saveOrUpdate(f.setSplitStatus(0));
                }
            }
        });
        return true;
    }

    /**
     * @param inputStream
     * @param rid
     * @param userId
     * @param type        1 word ,2 pdf
     *                                                              todo 纯文本模式    与上面一样 只是入库不一致
     */
    @SneakyThrows
    @Async
    public void extractFilesText(InputStream inputStream, Integer rid, Integer userId, Integer type, String path, Integer spilt) {
        List<FileDetails> fileDetails = new ArrayList<>();
        if (type == 0) {
            fileDetails = extractUtil.extract0(rid, userId, path);
        } else if (type == 1) {
            fileDetails = extractUtil.extractWord(inputStream, rid, userId);
        } else if (type == -1) {
            fileDetails = extractUtil.extractPdfBox(rid, userId, path);
        } else if (type == -2) {
            fileDetails = extractUtil.extractPdfBoxForFull(rid, userId, path);
        } else {
            fileDetails = extractUtil.extractPdf(inputStream, rid, userId);
        }
        if (fileDetails.size() == 0) {
//            return false;
        }
        List<FileDetailsTxt> insList = new ArrayList<>(100000);
        for (FileDetails fileDetail : fileDetails) {
            FileDetailsTxt newSin = new FileDetailsTxt();
            BeanUtils.copyProperties(fileDetail, newSin);
            insList.add(newSin);
        }
        insList.stream().forEach(f -> {
            detailTxtService.saveOrUpdate(f.setFId(rid));
            if (type == -2) {
                return;
            }

        });
//        return true;
    }


    /**
     * @param inputStream
     * @param rid
     * @param userId
     * @param type        1 word ,2 pdf
     */
    @SneakyThrows
    public List<FileDetailsTxt> extractFilesBackStr(InputStream inputStream, Integer rid, Integer userId, Integer type, String path) {
        List<FileDetails> fileDetails = new ArrayList<>();
        if (type == 0) {
            fileDetails = extractUtil.extract0(rid, userId, path);
        } else if (type == 1) {
            fileDetails = extractUtil.extractWord(inputStream, rid, userId);
        } else if (type == -1) {
            fileDetails = extractUtil.extractPdfBox(rid, userId, path);
        } else if (type == -2) {
            fileDetails = extractUtil.extractPdfBoxForFull(rid, userId, path);
        } else {
            fileDetails = extractUtil.extractPdf(inputStream, rid, userId);
        }


        List<FileDetailsTxt> insList = new ArrayList<>(100000);
        for (FileDetails fileDetail : fileDetails) {
            FileDetailsTxt newSin = new FileDetailsTxt();
            BeanUtils.copyProperties(fileDetail, newSin);
            insList.add(newSin);
        }

        return insList;
    }


    @SneakyThrows
    public boolean pics(Integer rid, Integer userId, String path) {

        List<FileDetails> fileDetailsArr = new ArrayList<FileDetails>();
        String[] split = path.split("###");//1.jpg
        for (String pdfPath : split) {
            pdfPath = uploadPath + pdfPath;
            String docx = minioUtil.upload(FileUtil.getInputStream(pdfPath), userId, DateUtil.today(), StrUtil.subAfter(pdfPath, "/", true), Scenario.view);
            FileDetails fileDetail = new FileDetails();
            fileDetail.setFId(rid);
            fileDetail.setTpye(2);
            fileDetail.setPath(docx);
            detailService.saveOrUpdate(fileDetail.setRid(rid));
            if (fileDetail.getTpye() == 2) {
                List<FileDetails> work = cutImageUtil.workNoUid(fileDetail.getPath(), fileDetail.getId(), fileDetail.getRid(), -1, userId);
                if (work.size() > 0) {
                    detailService.saveOrUpdateBatch(work);
                }
                detailService.saveOrUpdate(fileDetail.setSplitStatus(0));
            }
        }
        return true;
    }

    /**
     * @param inputStream
     * @param rid
     * @param userId
     * @param type
     */
    @SneakyThrows
    public void extractPdf(InputStream inputStream, Integer rid, Integer userId, String path) {
        List<FileDetails> fileDetails = new ArrayList<>();
        List<FileDetails> fileDetailsArr = extractUtil.extractPdf(inputStream, rid, userId);

        fileDetails.parallelStream().forEach(fileDetail -> {
            if (fileDetail.getTpye() == 2) {
                detailService.saveOrUpdate(fileDetail.setTpye(3).setFId(rid).setRid(rid));
                List<FileDetails> work = cutImageUtil.workNoUid(fileDetail.getPath(), fileDetail.getId(), fileDetail.getFId(), -1, userUtil.getUid());
                if (work.size() > 0) {
                    detailService.saveOrUpdateBatch(work);
                    detailService.updateById(fileDetail.setSplitStatus(0));
                }
            }
        });
    }

}
